<template>
  <el-card class="filter-card" shadow="never">
    <el-form :model="filterForm" inline>
      <el-form-item >
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateRangeChange">
        </el-date-picker>
      </el-form-item>

      <el-form-item v-if="needMerchantFilter">
        <el-select
          v-model="filterForm.merchant_id"
          placeholder="选择商户"
          clearable
          multiple
          collapse-tags
          filterable
          remote
          :remote-method="remoteSearchMerchants"
          :loading="merchantLoading"
          @change="handleMerchantSelectionChange">
          <el-option
            v-for="merchant in merchantList"
            :key="merchant.id"
            :label="`${merchant.merchant_name || merchant.name}（${merchant.contacts || '无联系人'}）`"
            :value="merchant.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item v-if="needCampaignFilter">
        <el-select
          v-model="filterForm.campaign_id"
          placeholder="选择活动"
          clearable
          multiple
          collapse-tags
          filterable
          remote
          :remote-method="remoteSearchCampaigns"
          :loading="campaignLoading"
          :disabled="!filterForm.merchant_id || filterForm.merchant_id.length === 0">
          <el-option
            v-for="campaign in campaignList"
            :key="campaign.id"
            :label="campaign.campaign_name || campaign.name"
            :value="campaign.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleApplyFilter">应用筛选</el-button>
        <el-button :loading="loading" @click="handleResetFilter" title="重置">
          <i class="el-icon-refresh-left"></i>
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { searchMerchants, getCampaignList } from '@/api/nfc'

export default {
  name: 'ReportFilter',
  props: {
    currentReportType: {
      type: String,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 筛选条件
      filterForm: {
        merchant_id: [],
        campaign_id: [],
        start_date: '',
        end_date: ''
      },
      dateRange: null,

      // 基础数据
      merchantList: [],
      campaignList: [],

      // 远程搜索与加载状态
      merchantLoading: false,
      campaignLoading: false,
      merchantKeyword: '',
      campaignKeyword: '',
      merchantPage: 1,
      campaignPage: 1,
      merchantLimit: 50,
      campaignLimit: 50,
      merchantSearchTimer: null,
      campaignSearchTimer: null
    }
  },
  computed: {
    // 是否需要显示商户筛选
    needMerchantFilter() {
      return ['points', 'commission', 'deposit', 'merchant', 'campaign', 'fission'].includes(this.currentReportType)
    },
    // 是否需要显示活动筛选
    needCampaignFilter() {
      return ['fission', 'campaign'].includes(this.currentReportType)
    }
  },
  mounted() {
    // 初始化默认时间范围（最近30天）
    const start = this.formatDate(new Date(Date.now() - 29 * 24 * 60 * 60 * 1000))
    const end = this.formatDate(new Date())
    this.filterForm.start_date = start
    this.filterForm.end_date = end
    this.dateRange = [start, end]
    
    // 加载基础数据
    this.loadBasicData()
  },
  beforeDestroy() {
    // 清理搜索定时器
    if (this.merchantSearchTimer) {
      clearTimeout(this.merchantSearchTimer)
      this.merchantSearchTimer = null
    }
    if (this.campaignSearchTimer) {
      clearTimeout(this.campaignSearchTimer)
      this.campaignSearchTimer = null
    }
  },
  methods: {
    // 简单日期格式化：返回 yyyy-MM-dd
    formatDate(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${d}`
    },

    // 加载基础数据
    async loadBasicData() {
      try {
        // 初始化商户远程搜索数据
        await this.remoteSearchMerchants('')
      } catch (error) {
        console.error('加载基础数据失败：', error)
        this.$message.error('加载基础数据失败')
      }
    },

    // 远程搜索商户（带防抖）
    remoteSearchMerchants(query) {
      // 清除之前的定时器
      if (this.merchantSearchTimer) {
        clearTimeout(this.merchantSearchTimer)
      }

      // 设置新的定时器，300ms后执行搜索
      this.merchantSearchTimer = setTimeout(() => {
        this.doSearchMerchants(query)
      }, 300)
    },

    // 实际执行商户搜索
    async doSearchMerchants(query) {
      try {
        this.merchantLoading = true
        this.merchantKeyword = query || ''
        const params = { keyword: this.merchantKeyword, page: this.merchantPage, limit: this.merchantLimit }
        const res = await searchMerchants(params)
        if (res && (res.code === 0 || res.code === 200)) {
          const list = res.data?.list || res.data || []
          this.merchantList = Array.isArray(list) ? list : []
        } else {
          console.warn('搜索商户API返回异常：', res)
          this.merchantList = []
        }
      } catch (e) {
        console.error('远程搜索商户失败', e)
        this.merchantList = []
        if (query !== '') { // 只有主动搜索时才显示错误提示
          this.$message.error('搜索商户失败，请稍后重试')
        }
      } finally {
        this.merchantLoading = false
      }
    },

    // 远程搜索活动（带防抖）
    remoteSearchCampaigns(query) {
      if (!this.filterForm.merchant_id || this.filterForm.merchant_id.length === 0) {
        this.campaignList = []
        return
      }

      // 清除之前的定时器
      if (this.campaignSearchTimer) {
        clearTimeout(this.campaignSearchTimer)
      }

      // 设置新的定时器，300ms后执行搜索
      this.campaignSearchTimer = setTimeout(() => {
        this.doSearchCampaigns(query)
      }, 300)
    },

    // 实际执行活动搜索
    async doSearchCampaigns(query) {
      try {
        this.campaignLoading = true
        this.campaignKeyword = query || ''
        
        // 构建请求参数，使用merchant_id数组格式
        const params = { 
          keyword: this.campaignKeyword, 
          merchant_id: this.filterForm.merchant_id, // 直接传递数组
          page: this.campaignPage, 
          limit: this.campaignLimit 
        }
        
        console.log('活动搜索请求参数:', params)
        const res = await getCampaignList(params)
        console.log('活动搜索响应:', res)
        
        if (res && (res.code === 0 || res.code === 200)) {
          // 兼容多种响应数据格式
          let list = []
          if (res.data) {
            // 优先尝试 res.data.list 格式（分页数据）
            list = res.data.list || res.data.data || res.data || []
          }
          
          this.campaignList = Array.isArray(list) ? list : []
          console.log(`成功加载 ${this.campaignList.length} 个活动`)
        } else {
          console.warn('搜索活动API返回异常：', res)
          this.campaignList = []
          // 提供更具体的错误信息
          const errorMsg = res?.message || res?.msg || '未知错误'
          if (query !== '') {
            this.$message.error(`搜索活动失败：${errorMsg}`)
          }
        }
        
      } catch (e) {
        console.error('远程搜索活动失败', e)
        this.campaignList = []
        
        // 网络错误或其他异常的用户友好提示
        let errorMessage = '搜索活动失败，请稍后重试'
        if (e.code === 'ECONNABORTED') {
          errorMessage = '请求超时，请检查网络连接'
        } else if (e.response?.status === 401) {
          errorMessage = '身份验证失败，请重新登录'
        } else if (e.response?.status >= 500) {
          errorMessage = '服务器暂时不可用，请稍后重试'
        }
        
        if (query !== '') { // 只有主动搜索时才显示错误提示
          this.$message.error(errorMessage)
        }
      } finally {
        this.campaignLoading = false
      }
    },

    // 日期范围变更处理
    handleDateRangeChange(value) {
      if (value && value.length === 2) {
        this.filterForm.start_date = value[0]
        this.filterForm.end_date = value[1]
      } else {
        this.filterForm.start_date = ''
        this.filterForm.end_date = ''
      }
      // 触发筛选条件变更事件
      this.emitFilterChange()
    },

    // 商户选择变更处理
    handleMerchantSelectionChange() {
      // 清空活动选择
      this.filterForm.campaign_id = []
      this.campaignList = []

      // 如果选择了商户，加载对应的活动列表
      if (this.filterForm.merchant_id && this.filterForm.merchant_id.length > 0) {
        this.remoteSearchCampaigns('')
      }
      
      // 触发筛选条件变更事件
      this.emitFilterChange()
    },

    // 应用筛选
    async handleApplyFilter() {
      this.$emit('apply-filter', this.getFilterData())
      this.$message.success('筛选条件应用成功')
    },

    // 重置筛选
    async handleResetFilter() {
      // 重置筛选表单
      this.filterForm = {
        merchant_id: [],
        campaign_id: [],
        start_date: '',
        end_date: ''
      }
      this.dateRange = null

      // 清空活动列表（因为没有选中商户）
      this.campaignList = []

      // 重新加载基础数据
      try {
        await this.loadBasicData()
        this.$emit('reset-filter', this.getFilterData())
        this.$message.success('筛选条件已重置')
      } catch (error) {
        console.error('重置筛选条件失败：', error)
        this.$message.error('重置筛选条件失败')
      }
    },

    // 获取当前筛选数据
    getFilterData() {
      return {
        ...this.filterForm
      }
    },

    // 触发筛选条件变更事件
    emitFilterChange() {
      this.$emit('filter-change', this.getFilterData())
    },

    // 设置筛选条件（供父组件调用）
    setFilterData(data) {
      this.filterForm = { ...this.filterForm, ...data }
      if (data.start_date && data.end_date) {
        this.dateRange = [data.start_date, data.end_date]
      }
    }
  }
}
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
}

.filter-card .el-form-item {
  margin-bottom: 0;
}
</style>